//
//  TJLoginViewController.swift
//  weibo
//
//  Created by 简祖明 on 16/7/27.
//  Copyright © 2016年 汤娟. All rights reserved.
//

import UIKit
import SVProgressHUD

class TJLoginViewController: TJBaseTableViewController,UIWebViewDelegate {
    
    let webView = UIWebView()
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        //设置导航栏
        setupNav()
        //设置页面网络请求
        //1.网址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=1241838180&redirect_uri=http://www.itheima.cn&language=en"
        //let URL = NSURL(fileURLWithPath: url)
        
        //2.创建请求
       let request = NSURLRequest(URL: NSURL(string: url)!)
        
        //3.网页加载
        webView.loadRequest(request)
        //4.设置代理
        webView.delegate = self
    }

    //设置界面导航栏的左右两边按钮
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
    }
    
    //MARK: - 返回按钮
    @objc private func dismiss() {
        
        //返回上一级
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    //MARK: - 自动填充按钮
    @objc private func auto() {
        //"双引号和系统冲突，改成''或者转义
        let js = "document.getElementById('userId').value ='18297318203';document.getElementById('passwd').value = '123xihuan'"
        //字符串转为js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

}

//MARK : - webView的代理方法
//截取含有code的的url,获取code
extension TJLoginViewController {
    
    //加载网络请求： true：webView加载这个请求  false:不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //https://api.weibo.com/oauth2/authorize?client_id=1241838180&redirect_uri=http://www.itheima.cn
        printLog(request.URL)
        //hasPrefix 获取前缀，absoluteString是url的绝对路径
        //1.对url字符串的可选判断
        if let urlString = request.URL?.absoluteString {
            
            //2.判断字符串的前缀
           if urlString.hasPrefix(RedrectURL){
            
            printLog(urlString)
            //http://www.itheima.cn/?code=ac36fb4b690e0456e2967bc8c9790b71
            
             //3.对字符串进行截取，来获取code
            //query截取的是?号后面的字符串   code ＝ .....
            if let code = request.URL?.query {
                //4.截取code=后面的字符串
                let subStr = code.substringFromIndex("code=".endIndex)
                printLog(subStr)
                //5.拿code 去换Token
                loadToken(subStr)
            }
            }
        }
        return true
    }
    
    //页面开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
        //等待的图标
        SVProgressHUD.show()
    }
    
    //页面完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //页面加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}

//MARK: - 拿code发送网络请求，换取Token
extension TJLoginViewController {
    //网络加载Token
    private func loadToken(code : String) {
        
        //1.网址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //2.网络请求方式POST
        //3.参数:(必选)
        /*
        必选	类型及范围	说明
       * client_id	true	string	申请应用时分配的AppKey。
       * client_secret	true	string	申请应用时分配的AppSecret。
       * grant_type	true	string	请求的类型，填写authorization_code
        
        grant_type为authorization_code时
        必选	类型及范围	说明
       * code	true	string	调用authorize获得的code值。
       * redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
        */
        
        //参数存入字典
        let params = ["client_id":AppKey,
                      "client_secret":AppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":RedrectURL
        ]
        printLog(params)
        //单例发送POST请求
        TJHTTPClient.shareInstance.request(.POST, URLString: urlString, parameters: params, progress:nil, success: { (_,JSON) -> Void in
           
            //let JSON : AnyObject
            printLog(JSON)
            
            //1.可选项要解包:if let,guard let,??,if
            guard let json = JSON else{
                printLog("json必须有值")
                return
            }
            
            //2.把AnyObject转换成字典类型  可选类型用as?转换
            let dict = json as! [String : AnyObject]
            //3.字典转模型
            let model = TJUserInfoModel(dict: dict)
            
            //获取个人信息(闭包里面要用self)
            self.loadPersonalInfo(model)
            
            printLog(model.access_token)
            
            
            }) { (_, error) -> Void in
                //失败展示错误信息
                SVProgressHUD.showErrorWithStatus(error.description)
        }
    }
}

//MARK: -测试Token,获取个人信息
extension TJLoginViewController {
    private func loadPersonalInfo(model : TJUserInfoModel){
        
        //1.URl网址
        let urlString = "https://api.weibo.com/2/users/show.json"
        /*
        必选	类型及范围	说明
        access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
        uid	false	int64	需要查询的用户ID
        */
        //2.拼接参数
        //2个参数都是可选的，if let,guard let,??,if
        guard let token = model.access_token,uid = model.uid else{
            printLog("token,uid必须有值")
            return
        }
        
        //拼接
        let params = ["access_token" : token,
                      "uid" : uid
        ]
        printLog(params)
        
        //3.查看请求方式
        TJHTTPClient.shareInstance.request(.POST, URLString: urlString, parameters: params, progress: nil, success: { (_, JSON) -> Void in
            
            printLog(JSON)
            
            //let JSON: AnyObject?
            //1.把AnyObject转为字典模型
            guard let json = JSON as? [String : AnyObject] else{
                return
            }
            
            //screen_name	string	用户昵称
            //profile_image_url	string	用户头像地址（中图），50×50像素
            //可选的用as?强转
            //let name = json ["screen_name"]
            //json ["screen_name"] 是AnyObject?类型的

            model.screen_name = json["screen_name"] as? String
            model.profile_image_url = json["profile_image_url"] as? String
            
            printLog(model.profile_image_url)
            
            //归档保存
            model.savemodel()
            
            }) { (_, error) -> Void in
                SVProgressHUD.showErrorWithStatus(error.description)
        }
    }
}
